<?php

namespace app\common\model;

use think\Model;

class Msg extends Model
{
    static function allUserMsg($user_id){
        $device_ids = Device::userDeviceId($user_id);
        $me = new self();
        $res=$me
            ->field("ctrl_device.*,ctrl_msg.id as msg_id,ctrl_msg.pull_msg,ctrl_msg.push_msg,ctrl_msg.updated_at")
            ->join("ctrl_device","ctrl_device.id = ctrl_msg.device_id")
            ->whereIn("device_id",$device_ids)->select();
        return $res;
    }

    static function pop_device_msg($device_id){
        $msg = new self();
        $msg_item = $msg->where("device_id", $device_id)
            ->where("push_msg", "<>", "")
            ->order("id asc")->find();
        if(!empty($msg_item)){
            $msg_item_id = $msg_item->id;
            self::destroy(['id'=>$msg_item_id]);
        }
        return $msg_item;
    }
    static function send($cmd){
        $device_id = $cmd->device_id;
        $msgs = $cmd->cmd;
        $msg_array = explode("+",$msgs);
        if(is_array($msg_array)){
            foreach($msg_array as $msg){
                self::create([
                    "device_id"=>$device_id,
                    "push_msg"=>$msg,
                ]);
            };
        }else{
            self::create([
                "device_id"=>$device_id,
                "push_msg"=>$msgs,
            ]);
        }
    }
}
